<template>
  <div class="container" style="height:85%">
    <!--    <UnifyTitle/>-->

    <base-header ref="baseheader" @onSearch="onSearch" :tagList="tagList"></base-header>


    <!-- 检索区 -->
    <div class="flex space-between" style="height:90%">
      <div class="tree-list pl5 pt15 pr5 mr12 bgFFF bdradius4" style="width: 290px;overflow: auto;">
        <div class="block">
          <org-structure @search="onTreeSearch"></org-structure>
        </div>
      </div>
      <div class="pl20 pr20 bgFFF bdradius4 btn-section" style="width: calc(100% - 300px)">
        <!-- 表头区 -->
        <div class="flex space-between mt10">
          <div class="flex flex-y-center">
            <button-menu @handleAdd="handleAdd" @batchDelete="batchDelete" @handleImport="importModal = true" @handleExport="daochu"></button-menu>
          </div>
          <div class="flex flex-y-center"></div>
        </div>
        <!-- 列表区 -->
        <BaseTable
          class="table"
          ref="table"
          :loading="tableLoading"
          v-model="criteria"
          :columns="columns"
          :data="tableData"
          :selection="true"
          @on-search="loadData"
          @selectionChange="selectionChange"
        >
        </BaseTable>
      </div>
    </div>

    <!--  查看抽屉  -->
    <base-drawers
      v-model="showViewDrawers"
      title="居民信息"
      :showButton="false"
      @input="cancelBt('showViewDrawers')"
    >
      <detail ref="detail" detail-request-name="residentDetail" log-request-name="residentOperatingLog" residentType="1"
              @labelSaveSuccess="labelSaveSuccess"></detail>
    </base-drawers>
    <!--  编辑抽屉  -->
    <base-drawers
      v-model="showDrawers"
      :title="modalTitle"
      @input="cancelBt('showDrawers')"
      :loading="drawerLoading"
      submitBtn="提交"
      @drawerSubmit="drawerSubmit"
    >
      <div>
        <Form ref="form" :rules="rules" :label-width="105" :model="form">
          <FormItem label="新增方式" v-if="addWayList.length">
            <RadioGroup v-model="addWay">
              <Radio v-for="item in addWayList" :key="item.value" :label="item.value">{{ item.label }}</Radio>
            </RadioGroup>
          </FormItem>
          <div v-if="addWay === '1'">
            <FormItem prop="name" label="居民姓名">
              <Input
                type="text"
                placeholder="请输入居民姓名"
                clearable
                maxlength="20"
                v-model="form.name"
                :disabled="formDisabled"
                style="width: 280px"
              /></FormItem>
            <FormItem prop="tag" label="标签">
              <Select v-model="form.tagIdList" multiple transfer style="width: 280px" placeholder="请选择标签">
                <OptionGroup :label="item.tagName" v-for="item in tagList" :key="item.id">
                  <Option v-for="itemC in item.children" :value="itemC.id" :key="itemC.id">{{ itemC.tagName }}</Option>
                </OptionGroup>
              </Select>
            </FormItem>
            <FormItem prop="idCard" label="身份证号">
              <Input
                type="text"
                placeholder="请输入身份证号"
                maxlength="18"
                clearable
                v-model="form.idCard"
                :disabled="formDisabled"
                style="width: 280px"
              /></FormItem>
            <FormItem prop="phone" label="联系电话">
              <Input
                type="text"
                placeholder="请输入联系电话"
                clearable
                maxlength="11"
                v-model="form.phone"
                style="width: 280px"
              /></FormItem>
            <FormItem prop="address" label="户籍所在地">
              <Input
                type="text"
                placeholder="请输入户籍所在地"
                clearable
                maxlength="50"
                v-model="form.address"
                style="width: 280px"
              /></FormItem>
          </div>
          <FormItem prop="year" label="上传表格" v-else>
            <Button
              type="primary"
              class="flex flex-y-center flex-x-center"
              style="height: 28px"
              @click="importModal = true"
            >导入人员
            </Button
            >
          </FormItem>
        </Form>
      </div>
    </base-drawers>
    <!--  减员抽屉  -->
    <base-drawers
      v-model="showDrawersReduce"
      :title="modalTitle"
      @input="cancelBt('showDrawersReduce')"
      :loading="drawerLoading"
      submitBtn="提交"
      @drawerSubmit="drawerSubmitReduce"
    >
      <div>
        <Form ref="formReduce" :rules="rulesReduce" :label-width="105" :model="formReduce">
          <FormItem prop="pickDate" label="减员时间">
            <DatePicker
              v-model="formReduce.pickDate"
              type="year"
              clearable
              placeholder="请选择减员时间"
              format="yyyy"
              :transfer="true"
              :editable="false"
              :disabled="true"
              style="width: 280px"
            ></DatePicker>
          </FormItem>
          <FormItem prop="name" label="居民姓名">
            <Input
              type="text"
              placeholder="请输入居民姓名"
              clearable
              maxlength="20"
              v-model="formReduce.name"
              :disabled="true"
              style="width: 280px"
            /></FormItem>
          <FormItem prop="idCard" label="身份证号">
            <Input
              type="text"
              placeholder="请输入身份证号"
              maxlength="18"
              clearable
              v-model="formReduce.idCard"
              :disabled="true"
              style="width: 280px"
            /></FormItem>
          <FormItem prop="deletedReason" label="减员原因">
            <Input
              type="textarea"
              placeholder="请输入减员原因"
              :rows="6"
              v-model="formReduce.deletedReason"
              style="width: 280px"
            /></FormItem>
        </Form>
      </div>
    </base-drawers>
    <!--  享受政策抽屉  -->
    <base-drawers
      v-model="showDrawersPolicy"
      :title="modalTitle"
      @input="cancelBt('showDrawersPolicy')"
      :loading="drawerLoading"
      submitBtn="提交"
      @drawerSubmit="drawerSubmitPolicy"
    >
      <div>
        <Form ref="formPolicy" :rules="rulesPolicy" :label-width="105" :model="formPolicy">
          <FormItem prop="pickDate" label="享受时间">
            <DatePicker
              v-model="formPolicy.pickDate"
              type="year"
              clearable
              placeholder="请选择享受时间"
              format="yyyy"
              :transfer="true"
              :editable="false"
              :disabled="true"
              style="width: 280px"
            ></DatePicker>
          </FormItem>
          <FormItem prop="name" label="居民姓名">
            <Input
              type="text"
              placeholder="请输入居民姓名"
              clearable
              maxlength="20"
              v-model="formPolicy.name"
              :disabled="true"
              style="width: 280px"
            /></FormItem>
          <FormItem prop="idCard" label="身份证号">
            <Input
              type="text"
              placeholder="请输入身份证号"
              maxlength="18"
              clearable
              v-model="formPolicy.idCard"
              :disabled="true"
              style="width: 280px"
            /></FormItem>
          <FormItem prop="enjoyType" label="政策类型">
            <Select
              v-model="formPolicy.enjoyType"
              transfer
              style="width: 280px"
              placeholder="请选择政策类型"
            >
              <Option :value="1">社保</Option>
              <Option :value="2">医保</Option>
            </Select>
          </FormItem>
          <FormItem prop="enjoyAmount" label="享受金额">
            <Input
              type="number"
              placeholder="请输入享受金额"
              clearable
              v-model="formPolicy.enjoyAmount"
              style="width: 280px"
              show-word-limit
              maxlength="8"
              @on-change="formPolicyenjoyAmount"
            /></FormItem>
          <FormItem prop="reason" label="享受原因">
            <Input
              type="textarea"
              placeholder="请输入享受原因"
              :rows="6"
              v-model="formPolicy.reason"
              style="width: 280px"
            />
          </FormItem>
        </Form>
      </div>
    </base-drawers>

    <!-- 删除公共组件弹框 -->
    <Delete
      ref="delt"
      title="删除"
      :content="'删除后将无法恢复，确定删除？'"
      :isVisble="false"
      :delModal="true"
      :delLoading="delLoading"
      @modalConfirmTrue="modalConfirmTrue"
    />

    <!-- 导入数据弹窗 -->
    <import-modal
      :importModal="importModal"
      titleText="导入人员"
      requestUrl="/data/import/upload/resident-excel"
      downloadTempUrl="/t/%E5%B1%85%E6%B0%91%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
      :importType="1"
      @cancel="importModal = false"
      @success="chenggdaoru"/>
  </div>
</template>

<script>
import FromOne from "@/libs/jss/FormValidation";
import BaseHeader from './components/base-header';
import BaseDrawers from "_c/base-drawers/base-drawers";
import labelInfo from "_c/labelInfo/labelInfo";
import Detail from "./components/detail";
import importModal from "_c/importModal/importModal";
import orgStructure from "_c/orgStructure/orgStructure";

export default {
  components: {
    BaseHeader,
    BaseDrawers,
    labelInfo,
    Detail,
    importModal,
    orgStructure,
  },
  data() {
    return {
      tableLoading: false,
      tableData: [], // 列表绑定数据
      tagList: [],
      /**
       * 查询条件
       */
      criteria: {
        total: 0,
        page: {
          current: 1,
          size: 10,
        },
      },
      /**
       * 表格字段
       */
      columns: [
        {
          fixed: "left",
          title: "姓名",
          key: "name",
          width: 150,
          align: "left",
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "身份证号",
          key: "idCard",
          align: "left",
          width: 190,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          render: (h, params) => {
            return h("span", {style: {textAlign: "left"}},
              this.commonFn(params.row.idCard, 6, 4)
            );
          },
        },
        {
          title: "联系电话",
          key: "phone",
          align: "left",
          width: 170,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "户籍所在地",
          key: "address",
          align: "left",
          width: 180,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "添加时间",
          key: "createDate",
          align: "left",
          minWidth: 180,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          render: (h, params) => {
            return h(
              "span",
              {style: {textAlign: "left"}},
              this.parseTime(params.row.createDate, "{y}-{m}-{d}")
            );
          },
        },
        {
          title: "来源",
          key: "source",
          align: "left",
          width: 100,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          //  1-主动添加 2-批量导入3-缴费补充
          render: (h, params) => {
            let source = "";
            if (params.row.source == 1) {
              source = "主动添加";
            } else if (params.row.source == 2) {
              source = "批量导入";
            } else if (params.row.source == 3) {
              source = "缴费补充";
            }
            return h(
              "span",
              {style: {textAlign: "left"}},
              source
            );
          },
        },
        {
          title: "标签",
          key: "tagList",
          align: "left",
          minWidth: 400,
          render: (h, params) => {
            var arr = []
            if (params.row.tagList) {
              for (let i = 0; i < params.row.tagList.length; i++) {
                arr.push(params.row.tagList[i].tagName)
              }
            }
            return (
              <div>
                <labelInfo labelInfo={arr}></labelInfo>
              </div>
            );
          },
        },
      ],


      batchSelectionData: [],
      delLoading: false,  // 删除按钮loading
      modalTitle: "",
      //查看
      showViewDrawers: false,
      // 编辑
      showDrawers: false,
      drawerLoading: false,
      form: {},
      formDisabled: false,  // 身份证号、姓名 只读
      form1: {},
      addWay: "1",
      addWayList: [],
      rules: {
        name: [{
          required: true,
          message: "请输入居民姓名",
          trigger: "blur",
        }],
        phone: [{
          required: true,
          message: "请输入正确的电话",
          trigger: "blur",
          validator: FromOne.FormValidate.FormOne().phone,
        }],
        idCard: [{
          required: true,
          message: "请输入正确的身份证号",
          trigger: "blur",
          validator: FromOne.FormValidate.FormOne().id,
        }],
      },
      importModal: false,


      // 减员
      showDrawersReduce: false,
      formReduce: {},
      rulesReduce: {
        pickDate: [
          {
            type: "date",
            required: true,
            message: "请选择减员时间",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入居民姓名",
            trigger: "blur",
          },
        ],
        idCard: [
          {
            required: true,
            message: "请输入正确的身份证号",
            trigger: "blur",
            validator: FromOne.FormValidate.FormOne().id,
          },
        ],
        deletedReason: [
          {
            required: true,
            message: "请选择减员原因",
            trigger: "change",
          },
        ],
      },


      // 享受政策
      showDrawersPolicy: false,
      formPolicy: {},
      rulesPolicy: {
        pickDate: [
          {
            type: "date",
            required: true,
            message: "请选择享受时间",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入居民姓名",
            trigger: "blur",
          },
        ],
        idCard: [
          {
            required: true,
            message: "请输入正确的身份证号",
            trigger: "blur",
            validator: FromOne.FormValidate.FormOne().id,
          },
        ],
        enjoyType: [
          {
            required: true,
            type: "number",
            message: "请选择政策类型",
            trigger: "change",
          },
        ],
        enjoyAmount: [
          {
            required: true,
            message: "请输入享受金额",
            trigger: "change",
          },
          {
            validator:function (rule, value, callback) {
              var reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/;
              if (!Number(value) || !reg.test(value)) {
                callback("请输入正确的享受金额");
              }else {
                callback();
              }
            },
            trigger: "change"
          },
        ],
        reason: [
          {
            required: true,
            message: "请输入享受原因",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {},
  watch: {},
  created() {
    let buttonMenu = this.buttonMenu(this.$route.name);
    this.columns.push(this.columnMenu(buttonMenu.buttonRight, this));
    this.getTagList();
  },
  methods: {
    formPolicyenjoyAmount(){
      this.$nextTick(() =>{
        if(this.formPolicy.enjoyAmount.length > 8){
          this.formPolicy.enjoyAmount = this.formPolicy.enjoyAmount.slice(0,8)
        }
      })
    },
    // 导出
    daochu(){
      let data = {
        ...this.criteria,
      };
      this.APIS.getResidentExport(data).then((res) => {
        const name = '参保人员列表'
        const blob = new Blob([res], { type: "application/vnd.ms-excel" });
        var url = window.URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", name);
        document.body.appendChild(link);
        link.click();
      })
    },
    onTreeSearch(data) {
      this.criteria.deptIdSet = data.deptIdSet.length ? data.deptIdSet : [data.qywechatDeptId];
      this.criteria.page.current = 1;
      this.criteria.total = 0;
      this.loadData();
    },
    onSearch(data) {
      this.criteria = {
        ...data,
        deptIdSet: this.criteria.deptIdSet,
      }
      this.loadData();
    },
    // 获取标签列表
    getTagList() {
      this.APIS.tagList().then((res) => {
        if (res.code == 20000) {
          this.tagList = this.handleTree(res.data);
        } else {
          this.$Message.error(res.message)
        }
      });
    },
    // 初始化获取列表数据
    loadData() {
      this.tableLoading = true;
      let data = {
        ...this.criteria,
      };
      this.APIS.residentList(data).then((res) => {
        this.tableLoading = false;
        if (res.code == 20000) {
          this.criteria.total = res.data.total;
          this.tableData = res.data.records;
        } else {
          this.$Message.error(res.message)
        }
      }).catch(err => {
        this.tableLoading = false;
      });
    },
    handleAdd() {
      this.modalTitle = "新建居民";
      this.drawerLoading = false;
      if (localStorage.getItem("import") === "true") {
        this.addWayList = [{
          value: "1",
          label: "手动新增"
        }, {
          value: "2",
          label: "导入数据"
        }]
      }
      this.formDisabled = false;
      this.showDrawers = true;
    },
    // 查看
    handleView(params) {
      this.showViewDrawers = true;
      this.$refs.detail.getDetail(params);
    },
    //  标签保存成功后加载数据
    labelSaveSuccess(data) {
      this.loadData();
    },
    // 编辑
    handleEdit(params) {
      // 详情
      this.APIS.residentDetail({id: params.id}).then((res) => {
        if (res.code == 20000) {
          this.form1 = JSON.parse(JSON.stringify(res.data));
          this.form = JSON.parse(JSON.stringify(res.data));
          if (this.form.tagList && this.form.tagList.length) {
            this.form.tagIdList = this.form.tagList.map(item => item.id);
          }
          this.modalTitle = "编辑居民";
          this.drawerLoading = false;
          this.formDisabled = true;
          this.showDrawers = true;
        } else {
          this.$Message.error(res.message)
        }
      });
    },
    drawerSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.drawerLoading = true;
          if (this.form.id == null || this.form.id == undefined || this.form.id === "") {
            this.APIS.residentAdd(this.form).then((res) => {
              this.drawerLoading = false;
              if (res.code == 20000) {
                this.$Message.success("新建成功");
                this.cancelBt('showDrawers');
                this.loadData();
              } else {
                this.$Message.error(res.message)
              }
            })
          } else {
            let data = {
              id: this.form.id,
            }
            for (let i in this.form) {
              if (this.form[i] !== this.form1[i]) {
                data[i] = this.form[i];
              }
            }
            this.APIS.residentUpdate(data).then((res) => {
              this.drawerLoading = false;
              if (res.code == 20000) {
                this.$Message.success("编辑成功");
                this.cancelBt('showDrawers');
                this.loadData();
              } else {
                this.$Message.error(res.message)
              }
            });
          }
        }
      });
    },
    // 关闭抽屉
    cancelBt(drawerName) {
      this[drawerName] = false;
      this.form = {};
      this.addWayList = [];
      this.addWay = "1";
      this.$refs.form.resetFields();

      this.formReduce = {};
      this.$refs.formReduce.resetFields();

      this.formPolicy = {};
      this.$refs.formPolicy.resetFields();
    },
    // 删除
    handleDelete(params) {
      this.$refs.delt.instance(params);
    },
    modalConfirmTrue(data) {
      this.delLoading = true;
      // 删除总事件
      this.APIS.residentDel({id: data.id}).then((res) => {
        if (res.code == 20000) {
          this.delLoading = false;
          this.$refs.delt.showDelModal = false;
          this.$Message.success("删除成功");
          this.loadData();
        } else {
          this.delLoading = false;
          this.$Message.error(res.message)
        }
      });
    },

    selectionChange(data) {
      this.batchSelectionData = data;
    },
    //  批量删除
    batchDelete() {
      if (this.batchSelectionData.length > 0) {
      } else {
        this.$Message.warning("请先勾选数据");
      }
    },
    chenggdaoru() {
      this.importModal = false;
      this.criteria.page.current = 1;
      this.criteria.page.total = 0;
      this.loadData();
    },


    // 快捷减员
    handleReduce(params) {
      this.formReduce = {
        ...params,
      }
      //  减员时间 默认选中明年
      let date = new Date().getFullYear() + 1;
      this.formReduce.pickDate = date.toString();
      this.formReduce.year = date.toString();
      this.modalTitle = "减员";
      this.showDrawersReduce = true;
    },
    drawerSubmitReduce() {
      this.$refs.formReduce.validate((valid) => {
        if (valid) {
          this.drawerLoading = true;
          let data = {
            id: this.formReduce.id,
            year: this.formReduce.year,  // 年份
            deletedReason: this.formReduce.deletedReason  // 原因
            // remark: this.formPolicy.remark,
          }
          this.APIS.residentQuickDelete(data).then((res) => {
            this.drawerLoading = false;
            if (res.code == 20000) {
              this.$Message.success("提交成功");
              this.cancelBt('showDrawersReduce');
              this.loadData();
            } else {
              this.$Message.error(res.message);
            }
          });
        }
      });
    },

    // 快捷享受政策
    handlePolicy(params) {
      this.formPolicy = {
        ...params,
      }
      //  享受时间 默认选中明年
      let date = new Date().getFullYear() + 1;
      this.formPolicy.pickDate = date.toString();
      this.formPolicy.year = date.toString();
      this.modalTitle = "享受政策";
      this.showDrawersPolicy = true;
    },
    drawerSubmitPolicy() {
      this.$refs.formPolicy.validate((valid) => {
        if (valid) {
          if(this.formPolicy.enjoyAmount == 0 ){
            this.$Message.warning('享受金额不可为零');
            return false
          }
          this.drawerLoading = true;
          let data = {
            idCard: this.formPolicy.idCard,
            name: this.formPolicy.name,
            // remark: this.formPolicy.remark,
            enjoyAmount: this.formPolicy.enjoyAmount,  // 享受金额
            enjoyType: this.formPolicy.enjoyType,   // 享受类型 1社保 2 医保
            reason: this.formPolicy.reason  // 原因
          }
          this.APIS.residentQuickPolicy(data).then((res) => {
            this.drawerLoading = false;
            if (res.code == 20000) {
              this.$Message.success("提交成功");
              this.cancelBt('showDrawersPolicy');
              this.loadData();
            } else {
              this.$Message.error(res.message);
            }
          });
        }
      });
    },
  },
};
</script>


<style lang="less" scoped>
@import "../setUp/contactsManagement/index";

.table {
  /deep/ .ivu-card-body {
    padding: 0 !important;
  }
}
</style>
